package com.daisuxia.back.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.daisuxia.back.service.TaskJob;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.ExcelRead;
import com.daisuxia.back.utils.ExcelUtil;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.dao.IChannelReportDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BackLog;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ChannelDynamic;
import com.daisuxia.web.pojo.ChannelInfo;
import com.daisuxia.web.pojo.ChannelRate;
import com.daisuxia.web.pojo.ChannelReport;
import com.daisuxia.web.pojo.ChannelSuperInfo;
import com.daisuxia.web.pojo.PhoneUrl;
import com.daisuxia.web.pojo.SeriesObj;
import com.daisuxia.web.pojo.TotalJson;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IChannelInfoService;
import com.daisuxia.web.service.IChannelReportService;
import com.daisuxia.web.service.ILoanMoneyReportService;
import com.daisuxia.web.service.ILoanReportService;
import com.daisuxia.web.service.IPhoneUrlService;
import com.daisuxia.web.service.IThirdChannelReportService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.Base64Utils;
import com.daisuxia.web.util.ConfigConstant;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.QrCodeUtil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import redis.clients.jedis.JedisCluster;


@Controller
@RequestMapping("channel/")
public class ChannelInfoController extends BaseController {

	private static Logger logger = LoggerFactory
			.getLogger(ChannelInfoController.class);

	@Autowired
	private IChannelInfoService channelInfoService;
	@Autowired
	private IChannelReportService channelReportService;
	@Autowired
	private IUserService userService;
	@Autowired
	IChannelReportDao channelReportDao;
	@Autowired
	ILoanReportService loanReportService;
	@Autowired
	IThirdChannelReportService thirdChannelReportService;
	@Autowired
	TaskJob taskjob;
	@Autowired
	JedisCluster jedisCluster;
	
	@Autowired
	ILoanMoneyReportService loanmoneyReportService;
	@Autowired
	IPhoneUrlService phoneUrlService;
	/**
	 * 推广渠道分页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelInfoPage")
	public String getChannelInfoPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<ChannelInfo> pageConfig = channelInfoService
					.findPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			String nowTime = null;
//			thirdChannelReportService.pushAginUserReport(nowTime);
//			channelReportService.saveChannelReport(nowTime);
			
//			loanmoneyReportService.saveLoanMoneyReport("2017-03-30");
		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelInfoPage";
	}

	/**
	 * 推广员分页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelUserInfoPage")
	public String getChannelUserInfoPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = getParametersO(request);
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();
				
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelInfo> pageConfig = channelInfoService
					.findChannelUserPage(params);
			
			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			String bpath = request.getContextPath();
			model.addAttribute("bpath", bpath);

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelUserInfoPage";
	}

	/**
	 * 推广记录分页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelRecordPage")
	public String getChannelRecordPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();
				;
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelInfo> pageConfig = channelInfoService
					.findChannelRecordPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			// channelReportService.saveChannelReport();
		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelRecordPage";
	}

	/**
	 * 添加或修改推广渠道
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelInfo")
	public String saveUpdateChannelInfo(HttpServletRequest request,
			HttpServletResponse response, Model model, ChannelInfo channelInfo) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		
		try {
			/*List<ChannelSuperInfo> channelSuperList = channelInfoService.findSuperAll(null);
			List<ChannelRate> channelRateList = channelInfoService.findChannelRateAll(null);*/
			List<ChannelSuperInfo> channelSuperList = channelInfoService.findSuperAll();
			List<ChannelRate> channelRateList = channelInfoService.findChannelRateAll();
			model.addAttribute("channelSuperList", channelSuperList);
			model.addAttribute("channelRateList", channelRateList);
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					// 更新的页面跳转
					channelInfo = channelInfoService.findOneChannelInfo(params);
					model.addAttribute("channelInfo", channelInfo);
				}
				url = "userInfo/editChannelInfo";
			} else {
				channelInfo.setStatus(1);
				// 更新操作
				if (channelInfo.getId() != null) {
					AESUtil aesEncrypt = new AESUtil();
					String passWord = MD5coding.MD5(aesEncrypt.encrypt(channelInfo.getChannelPassword(),""));// 加密
					channelInfo.setChannelPassword(passWord);
					channelInfo.setCreatedAt(new Date());
					channelInfoService.updateById(channelInfo);
				} else {
					//添加操作
					ChannelInfo codeChannelInfo = null;
					HashMap<String, Object> queryMap = new HashMap<String, Object>();
					queryMap.put("channelCode",channelInfo.getChannelCode());
					codeChannelInfo = channelInfoService.findOneChannelInfo(queryMap);
			
					if (codeChannelInfo != null) {
						SpringUtils.renderDwzResult(response, false,
								"渠道编码已存在",
								DwzResult.CALLBACK_CLOSECURRENT, params
										.get("parentId").toString());
						return url;
					}
					AESUtil aesEncrypt = new AESUtil();
					String passWord = MD5coding.MD5(aesEncrypt.encrypt(channelInfo.getChannelPassword(),""));// 加密
		
					channelInfo.setChannelPassword(passWord);
					channelInfo.setUpdatedAt(new Date());
					channelInfoService.insert(channelInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}

	/**
	 * 分配推广员
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */
	@RequestMapping("relChannelUser")
	public String releaseRedenvelope(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		// 更新的页面跳转
		ChannelInfo channelInfo = channelInfoService.findOneChannelInfo(params);
		model.addAttribute("grant", true);
		model.addAttribute("channelInfo", channelInfo);

		return "userInfo/relChannelUser";
	}
 
	/**
	 * 添加或修改推广员
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelUserInfo")
	public String saveUpdateChannelUserInfo(HttpServletRequest request,
			HttpServletResponse response, Model model, User user) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					ChannelInfo channelInfo = channelInfoService
							.findOneChannelInfo(params);
					// 更新的页面跳转
					// channelInfo =
					// channelInfoService.findOneChannelInfo(params);
					// model.addAttribute("channelInfo", channelInfo);
					model.addAttribute("channelInfo", channelInfo);
				}
				url = "userInfo/saveChannelUser";
			} else {
				// 更新或者添加操作
				if (user.getId() != null) {

				} else {
					if (params.containsKey("channelId")) {
						User validPhoneUser = null;
						User validIDCardUser = null;
						Map<String, Object> queryMap = new HashMap<String, Object>();
						queryMap.put("userPhone", user.getUserPhone());
						validPhoneUser = userService
								.searchByUphoneAndUid(queryMap);

						if (validPhoneUser != null) {
							SpringUtils.renderDwzResult(response, false,
									"操作失败，该手机号已存在",
									DwzResult.CALLBACK_CLOSECURRENT, params
											.get("parentId").toString());
							return url;
						}
						else {
							HashMap<String, Object> map = new HashMap<String, Object>();
							String ip = this.getIpAddr(request);

							AESUtil aesEncrypt = new AESUtil();
							String passWord = MD5coding.MD5(aesEncrypt.encrypt(
									ConfigConstant
											.getConstant(Constant.DEFAULT_PWD),
									""));// 加密
							user.setUserFrom(params.get("channelId").toString());
							user.setCreateIp(ip);
							user.setPassword(passWord);
							user.setUserName(user.getUserPhone());
							user.setEquipmentNumber(user.getUserPhone());// 设备号
							userService.saveUser(user);
							map.put("userPhone", user.getUserPhone());
							User findUser = userService
									.searchUserByCheckTel(map);
							if (findUser != null) {

								String inviteUserid = Base64Utils
										.encodeStr(findUser.getId());

								Map<String, String> keys = SysCacheUtils
										.getConfigParams(BackConfigParams.APP_IMG_URL);
								String appurl = keys.get("qrcode_URL");
								String qrurl = appurl
										+ request.getContextPath() + "/"
										+ "act/light-loan-xjx-beta?invite_code="
										+ inviteUserid + "&user_from="
										+ user.getUserFrom();
								if("2".equals(params.get("channelNew"))){
									 qrurl = appurl
											+ request.getContextPath() + "/"
											+ "act/light-loan-xjxNew?invite_code="
											+ inviteUserid + "&user_from="
											+ user.getUserFrom();
								}
								
    //TODO修改文件地址，需要根据服务器进行配置进行修改
								String qrName = MD5coding.MD5(String
										.valueOf(user.getId())) + ".jpg";// 二维码图片名称
								String savePath =  Constant.FILEPATH + "/"
										+ Constant.QR_FILEPATH + "/" + qrName;
								String qrfileRealPath =  Constant.FILEPATH + "/"
														+ Constant.QR_FILEPATH
														+ "/" + qrName; // 二维码本地存储路径

								String logoPathDir = request
										.getSession()
										.getServletContext()
										.getRealPath(
												"common/web/images/logo_qr_xjx.png"); // LOGO获取本地存储路径

								QrCodeUtil.encode(qrurl, 300, 300, logoPathDir,
										qrfileRealPath);

								params.put("userId", findUser.getId());
								params.put("channelId", params.get("channelId"));
								params.put("relPath",
										savePath.replaceAll("\\\\", "\\/"));
								params.put("remark", qrurl);

								channelInfoService
										.insertChannelUserInfo(params);
							} else {
								SpringUtils.renderDwzResult(response, false,
										"添加用户失败",
										DwzResult.CALLBACK_CLOSECURRENT, params
												.get("parentId").toString());
							}
						}
					} else {
						SpringUtils.renderDwzResult(response, false, "添加失败",
								DwzResult.CALLBACK_CLOSECURRENT,
								params.get("right_id").toString());
						return url;
					}
					// channelInfoService.updateById(channelInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}

	/**
	 * 获取推广员动态信息
	 * @param request
	 * @param response
	 * @param model
	 * @param user
     * @return
     */
	@RequestMapping("getDynamicInfo")
	public String getDynamicInfo(HttpServletRequest request,HttpServletResponse response, Model model, User user){
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					ChannelInfo channelInfo = channelInfoService.findOneChannelInfoNew(params);
					model.addAttribute("channelInfo", channelInfo);
				}
				url = "userInfo/saveDynamicChannelUser";
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
								+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}


	/**
	 *
	 * 推广员动态添加
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveDynamic")
	public String saveDynamic(@RequestParam("registerPic")CommonsMultipartFile registerPic,
							  @RequestParam("downloadPic")CommonsMultipartFile downloadPic,
							  HttpServletRequest request,HttpServletResponse response, Model model, User user) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
				// 更新或者添加操作
				if (user.getId() != null) {

				} else {
					if (params.containsKey("channelId")) {
						User validPhoneUser = null;
						User validIDCardUser = null;
						Map<String, Object> queryMap = new HashMap<String, Object>();
						queryMap.put("userPhone", user.getUserPhone());
						validPhoneUser = userService.searchByUphoneAndUid(queryMap);

						if (validPhoneUser != null) {
							SpringUtils.renderDwzResult(response, false,"操作失败，该手机号已存在",DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
							return url;
						}
						else {
							HashMap<String, Object> map = new HashMap<String, Object>();
							String ip = this.getIpAddr(request);

							AESUtil aesEncrypt = new AESUtil();
							String passWord = MD5coding.MD5(aesEncrypt.encrypt(ConfigConstant.getConstant(Constant.DEFAULT_PWD),""));// 加密
							user.setUserFrom(params.get("channelId").toString());
							user.setCreateIp(ip);
							user.setPassword(passWord);
							user.setUserName(user.getUserPhone());
							user.setEquipmentNumber(user.getUserPhone());// 设备号
							userService.saveUser(user);
							map.put("userPhone", user.getUserPhone());
							User findUser = userService.searchUserByCheckTel(map);
							if (findUser != null) {

								String inviteUserid = Base64Utils.encodeStr(findUser.getId());

								Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.APP_IMG_URL);
								String appurl = keys.get("H5_DYNAMIC_URL");
								String qrurl = appurl
										+ "cashman_h5/act/light-loan-xjx-dynamic?invite_code="
										+ inviteUserid + "&user_from="
										+ user.getUserFrom();
								if("2".equals(params.get("channelNew"))){
									qrurl = appurl
											+ "cashman_h5/act/light-loan-xjx-dynamic?invite_code="
											+ inviteUserid + "&user_from="
											+ user.getUserFrom();
								}

								String qrName = MD5coding.MD5(String
										.valueOf(user.getId())) + ".jpg";// 二维码图片名称
								String savePath = "/" + Constant.FILEPATH + "/"
										+ Constant.QR_FILEPATH + "/" + qrName;
								String qrfileRealPath = request
										.getSession()
										.getServletContext()
										.getRealPath(
												"/" + Constant.FILEPATH + "/"
														+ Constant.QR_FILEPATH
														+ "/" + qrName); // 二维码本地存储路径

								String logoPathDir = request
										.getSession()
										.getServletContext()
										.getRealPath("common/web/images/logo_qr_xjx.png"); // LOGO获取本地存储路径

								QrCodeUtil.encode(qrurl, 300, 300, logoPathDir,qrfileRealPath);

								params.put("userId", findUser.getId());
								params.put("channelId", params.get("channelId"));
								params.put("relPath",savePath.replaceAll("\\\\", "\\/"));
								params.put("remark", qrurl);

								channelInfoService.insertChannelUserInfo(params);


								String registerPicUrl = getPicUrl(registerPic.getFileItem().getName(),registerPic.getInputStream(),params.get("channelId").toString(),"register");
								String downloadPicUrl = getPicUrl(downloadPic.getFileItem().getName(),downloadPic.getInputStream(),params.get("channelId").toString(),"download");
								logger.info(registerPicUrl + "  =======  " + downloadPicUrl);

								ChannelDynamic channelDynamic = new ChannelDynamic();
								channelDynamic.setChannelInfoId(Long.valueOf(params.get("channelId").toString()));
								channelDynamic.setRegisterPicUrl(registerPicUrl);
								channelDynamic.setDownloadPicUrl(downloadPicUrl);
								channelDynamic.setUserInfoId(Long.valueOf(findUser.getId()));
								channelInfoService.insertChannelDynamic(channelDynamic,user);

							} else {
								SpringUtils.renderDwzResult(response, false,
										"添加用户失败",
										DwzResult.CALLBACK_CLOSECURRENT, params
												.get("parentId").toString());
							}
						}
					} else {
						SpringUtils.renderDwzResult(response, false, "添加失败",
								DwzResult.CALLBACK_CLOSECURRENT,
								params.get("right_id").toString());
						return url;
					}
					// channelInfoService.updateById(channelInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());

		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
								+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}
    /**
     * 禁止处理
     * @param name
     * @param is
     * @param channelId
     * @param type
     * @return
     */
	private String getPicUrl(String name, InputStream is ,String channelId,String type) {
		String bucketName="xjxh5tg";
		String key = setPicName(channelId, type, name); //2017/06/渠道ID/reg_时间戳.jpg
		/*OSSUpload ossUpload = new OSSUpload();
		OSSModel ossModel = ossUpload.sampleUploadWithInputStream(bucketName, key, is);*/
		return null;
	}

	private String setPicName(String channelId, String type, String name) {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		return year + "/" + (month+1) + "/" + channelId + "/"+type+"_" + System.currentTimeMillis() + name.substring(name.indexOf("."));
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteChannelInfo")
	public void deleteChannelInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			channelInfoService.deleteChannelInfoById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteRole error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "删除用户成功" : "删除用户失败",
				DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());
	}

	/**
	 * 推广统计(渠道)
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */

	@RequestMapping("getChannelReportPage")
	public String getChannelReportPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = new HashMap<String, Object>();
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelReport> pageConfig = channelReportService
					.findPage(params);

			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		return "userInfo/channelReportPage";
	}

	/**
	 * 推广统计(地区)
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */

	@RequestMapping("getChannelPrReportPage")
	public String getChannelPrReportPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = new HashMap<String, Object>();
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelReport> pageConfig = channelReportService
					.findPrPage(params);

			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		return "userInfo/channelPrReportPage";
	}

	/**
	 * 推广统计(统计每个渠道商所有)
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */

	@RequestMapping("getChannelSumReportPage")
	public String getChannelSumReportPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = new HashMap<String, Object>();
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelReport> pageConfig = channelReportService
					.findSumPage(params);

			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		return "userInfo/channelSumReportPage";
	}

	/**
	 * 推广记录Excel
	 */
	@RequestMapping("channelRecordToExcel")
	public void channelRecordToExcel(HttpServletRequest request,
			HttpServletResponse response) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			params.put(Constant.PAGE_SIZE, 50000);
			int totalPageNum = channelInfoService.findParamsCount(params);
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "推广统计列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "注册用户", "注册用户手机号", "注册时间", "推广员姓名", "推广员电话",
					"渠道商名称", "负责人" };
			for (int i = 1; i <= totalPageNum; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<ChannelInfo> pm = channelInfoService
						.findChannelRecordPage(params);
				List<ChannelInfo> channelList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (ChannelInfo channelInfo : channelList) {
					Object[] conList = new Object[titles.length];
					conList[0] = channelInfo.getUserName();
					conList[1] = channelInfo.getUserTel();
					conList[2] = DateUtil.getDateFormat(
							channelInfo.getCreateTime(), "yy-MM-dd hh:mm:ss");
					conList[3] = channelInfo.getRealname();
					conList[4] = channelInfo.getUserPhone();
					conList[5] = channelInfo.getChannelName();
					conList[6] = channelInfo.getOperatorName();
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "放款列表", titles, contents, i,
						pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}
	}

	/**
	 * 推广统计excel
	 */
	@RequestMapping("channelReportToExcel")
	public void borrowChartExcel(HttpServletResponse response,
			HttpServletRequest request, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			int size = 50000;
			int total = 0;
			params.put(Constant.PAGE_SIZE, size);
			int totalPageNum = channelReportService.findParamsCount(params);
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "channelReport.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "渠道商", "日期", "注册量", "实名人数", "绑卡人数", "紧急联系人人数",
					"运营商认证", "支付宝人数", "芝麻人数", "工作信息人数", "申请借款人数", "借款成功人数",
					"通过率","新用户放款金额","老用户放款金额" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<ChannelReport> pm = channelReportService.findPage(params);
				List<ChannelReport> list = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (ChannelReport reports : list) {
					String[] conList = new String[titles.length];
					conList[0] = reports.getChannelName()==null?"":reports.getChannelName().toString();
					conList[1] = DateUtil.getDateFormat(reports.getReportDate(),
							"yyyy-MM-dd");
					conList[2] = reports.getRegisterCount().toString();
					conList[3] = reports.getAttestationRealnameCount().toString();
					conList[4] = reports.getAttestationBankCount().toString();
					conList[5] = reports.getContactCount().toString();
					conList[6] = reports.getJxlCount().toString();
					conList[7] = reports.getAlipayCount().toString();
					conList[8] = reports.getZhimaCount().toString();
					conList[9] = reports.getCompanyCount().toString();
					conList[10] = reports.getBorrowApplyCount().toString();
					conList[11] = reports.getBorrowSucCount().toString();
					conList[12] = reports.getPassRate().toString();
					conList[13] = (reports.getNewIntoMoney()
							.divide(new BigDecimal(100))).toString();
					conList[14] = (reports.getOldIntoMoney()
							.divide(new BigDecimal(100))).toString();
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "推广统计", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}
	}

	/**
	 * 推广统计(地区)excel
	 */
	@RequestMapping("channelPrReportToExcel")
	public void channelPrReportToExcel(HttpServletResponse response,
			HttpServletRequest request, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			int size = 50000;
			int total = 0;
			params.put(Constant.PAGE_SIZE, size);
			params.put("statusList", Arrays.asList(BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_BFHK, BorrowOrder.STATUS_YHK,
					BorrowOrder.STATUS_YQYHK, BorrowOrder.STATUS_YHZ,BorrowOrder.STATUS_YHZ,BorrowOrder.STATUS_KKZ));
//			params.put("borrowStatus", borrowStatus);
			int totalPageNum = channelReportService.findPrParamsCount(params);
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "channelReportPr.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "省份", "城市", "区域", "渠道商", "日期", "注册量", "实名人数",
					"绑卡人数", "紧急联系人人数", "运营商认证", "支付宝人数", "芝麻人数", "工作信息人数",
					"申请借款人数", "借款成功人数", "通过率", "放款总金额" };
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<ChannelReport> pm = channelReportService.findPrPage(params);
				List<ChannelReport> list = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (ChannelReport reports : list) {
					String[] conList = new String[titles.length];
					conList[0] = reports.getChannelProvince();
					conList[1] = reports.getChannelCity();
					conList[2] = reports.getChannelArea();
					conList[3] = reports.getChannelName().toString();
					conList[4] = DateUtil.getDateFormat(reports.getReportDate(),
							"yyyy-MM-dd");
					conList[5] = reports.getRegisterCount().toString();
					conList[6] = reports.getAttestationRealnameCount().toString();
					conList[7] = reports.getAttestationBankCount().toString();
					conList[8] = reports.getContactCount().toString();
					conList[9] = reports.getJxlCount().toString();
					conList[10] = reports.getAlipayCount().toString();
					conList[11] = reports.getZhimaCount().toString();
					conList[12] = reports.getCompanyCount().toString();
					conList[13] = reports.getBorrowApplyCount().toString();
					conList[14] = reports.getBorrowSucCount().toString();
					conList[15] = reports.getPassRate().toString();
					conList[16] = (reports.getIntoMoney()
							.divide(new BigDecimal(100))).toString();
					contents.add(conList);
				
				}
				ExcelUtil.buildExcel(workbook, "推广统计(地区)", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}
		 
	}

	/**
	 * 生成二维码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteChannelInfo")
	public void qrChannel(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			channelInfoService.deleteChannelInfoById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteRole error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "删除用户成功" : "删除用户失败",
				DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());
	}
	
	@RequestMapping("toAgainChannelReport")
	public String toAgainChannelReport(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, String> params =this.getParameters(request);
		model.addAttribute("params", params);
		String url=null;
		try {
			if("toJsp".equals(String.valueOf(params.get("type")))){
				url="userInfo/againReport";
			}else{
				if(params.get("nowTime")!=null){
					jedisCluster.del("channel_report");
					 channelReportService.saveChannelReport(String.valueOf(params.get("nowTime")));
				 }
				 SpringUtils.renderDwzResult(response, true,"操作成功，如要继续操作，请五分钟后再进行！", DwzResult.CALLBACK_CLOSECURRENT,params.get("parentId")
							.toString());
			}
		} catch (Exception e) {
			logger.error("againReport error", e);
		}
		return url;
	}
	
	/*****************************添加渠道上级信息***********************************/
	/**
	 * 渠道商管理分页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelSuperInfoPage")
	public String getChannelSuperInfoPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<ChannelSuperInfo> pageConfig = channelInfoService.findChannelSuperPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			String nowTime = null;
 
		} catch (Exception e) {
			logger.error("getchannelSuperInfoPage error", e);
		}
		return "channel/channelSuperInfoPage";
	}
	
	/**
	 * 短链接渠道管理
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getLinkPhoneUrlPage")
	public String getLinkChannelInfoPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<PhoneUrl> pageConfig = phoneUrlService.findPhoneUrlPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
		} catch (Exception e) {
			logger.error("getLinkChannelInfoPage error", e);
		}
		return "channel/channelUrlLinkPage";
	}
	/**
	 * 跳转到短链接页面
	 */
	@RequestMapping("getImportShortLinkPage")
	public String getImportShortLinkPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		return "channel/importShortLink";
	}
	/**
	 * 从Excel导入数据
	 * @throws ParseException 
	 */
	@RequestMapping(value="readExcel" ,method=RequestMethod.POST) 
	public void  readExcel(@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model) throws ParseException{  
        //String url="channel/channelUrlLinkPage";
		
			String msg = "操作成功";
			boolean succ = true;
	        if(file == null){  
	            model.addAttribute("msg", "文件为空!");
	            msg = "文件为空!";
				succ = false;
	            return ;  
	        }  
	        String name = file.getOriginalFilename();  
	        long size = file.getSize();  
	        if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){  
	        	model.addAttribute("msg", "文件名不存在或者文件内容为空!");
	        	msg = "文件名不存在或者文件内容为空!";
				succ = false;
	            return ; 
	        }  
	        //读取Excel数据到List中  
	        List<ArrayList<String>> list=null;
			try {
				list = new ExcelRead().readExcel(file);
			} catch (IOException e1) {
				 msg = "文件读取异常!";
				 succ = false;
				e1.printStackTrace();
			}  
	        //list中存的就是excel中的数据，可以根据excel中每一列的值转换成你所需要的值（从0开始）
	        PhoneUrl phoneUrl = null;  
	        List<PhoneUrl> phoneUrlList = new ArrayList<PhoneUrl>(); 
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");  
	        for(ArrayList<String> arr:list){                        
	        	phoneUrl= new PhoneUrl(); 
	        	if(arr.get(0).equals("")) {
	        		continue;
	        	}
	        	phoneUrl.setPhone(arr.get(0));
	        	phoneUrl.setUrl(arr.get(1));
	        	if(!arr.get(2).equals("")) {
	        		phoneUrl.setClickCount(Integer.parseInt(arr.get(2)));
	        	}
	        	phoneUrl.setIp(arr.get(3));
	        	if(!arr.get(4).equals("")) {
	        		phoneUrl.setStatisticTime(sdf.parse(arr.get(4)));
	        	}
	        	phoneUrlList.add(phoneUrl);  
	        }  
	    	try {
	    		phoneUrlService.insertBatch(phoneUrlList);
	    		model.addAttribute("msg", "短链接导入成功!");   
			} catch (Exception e) {
				 msg = "短链接导入异常!";
				 succ = false;
				logger.info(e.getMessage());
			}
	    	//SpringUtils.renderDwzResult(response, succ, msg, DwzResult.CALLBACK_CLOSECURRENTDIALOG);
	    	SpringUtils.renderDwzResult(response, succ, msg, DwzResult.CALLBACK_CLOSECURRENT);
    }
	/**
	 * 添加或修改推广渠道
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelSuperInfo")
	public String saveUpdateChannelSuperInfo(HttpServletRequest request,
			HttpServletResponse response, Model model, ChannelSuperInfo channelSuperInfo) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					// 更新的页面跳转
					channelSuperInfo = channelInfoService.findOneChannelSuperInfo(params);
					model.addAttribute("channelSuperInfo", channelSuperInfo);
				}
				url = "channel/editChannelSuperInfo";
			} else {
				 
				// 更新或者添加操作
				if (channelSuperInfo.getId() != null) {
//					AESUtil aesEncrypt = new AESUtil();
//					String passWord = MD5coding.MD5(aesEncrypt.encrypt(channelInfo.getChannelPassword(),""));// 加密
					
//					channelSuperInfo.setChannelPassword(passWord);
					channelInfoService.updateChannelSuperById(channelSuperInfo);
				} else {
					ChannelSuperInfo codeChannelInfo = null;
					HashMap<String, Object> queryMap = new HashMap<String, Object>();
					queryMap.put("channelSuperCode",channelSuperInfo.getChannelSuperCode());
					codeChannelInfo = channelInfoService.findOneChannelSuperInfo(queryMap);
			
					if (codeChannelInfo != null) {
						SpringUtils.renderDwzResult(response, false,
								"渠道编码已存在",
								DwzResult.CALLBACK_CLOSECURRENT, params
										.get("parentId").toString());
						return url;
					}
//					AESUtil aesEncrypt = new AESUtil();
//					String passWord = MD5coding.MD5(aesEncrypt.encrypt(channelInfo.getChannelPassword(),""));// 加密
					
//					channelInfo.setChannelPassword(passWord);
					channelInfoService.insertChannelSuperInfo(channelSuperInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}
	/**
	 * 删除渠道
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteChannel")
	public void deleteUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			channelInfoService.deleteById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteChannel error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "渠道删除成功" : "渠道删除失败", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
				.toString());
	}
	
	/*****************************添加渠道费率管理信息***********************************/
	/**
	 * 渠道商管理分页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelRatePage")
	public String getChannelRatePage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<ChannelRate> pageConfig = channelInfoService.findChannelRatePage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
 
		} catch (Exception e) {
			logger.error("getChannelRatePage error", e);
		}
		return "channel/channelRatePage";
	}
	
	
	
	/**
	 * 添加或修改推广渠道
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelRate")
	public String saveUpdateChannelRate(HttpServletRequest request,
			HttpServletResponse response, Model model, ChannelRate channelRate) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					// 更新的页面跳转
					channelRate = channelInfoService.findOneChannelRateInfo(params);
					model.addAttribute("channelRate", channelRate);
				}
				url = "channel/editChannelRate";
			} else {
				 
				// 更新或者添加操作
				if (channelRate.getId() != null) {
//					AESUtil aesEncrypt = new AESUtil();
//					String passWord = MD5coding.MD5(aesEncrypt.encrypt(channelInfo.getChannelPassword(),""));// 加密
					
//					channelSuperInfo.setChannelPassword(passWord);
					channelInfoService.updateChannelRateById(channelRate);
				} else {
					ChannelRate codeChannelRate = null;
					HashMap<String, Object> queryMap = new HashMap<String, Object>();
					queryMap.put("channelRateName",channelRate.getChannelRateName());
					codeChannelRate = channelInfoService.findOneChannelRateInfo(queryMap);
			
					if (codeChannelRate != null) {
						SpringUtils.renderDwzResult(response, false,
								"渠道费率名称已存在",
								DwzResult.CALLBACK_CLOSECURRENT, params
										.get("parentId").toString());
						return url;
					}

					channelInfoService.insertChannelRate(channelRate);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT,
						params.get("parentId").toString());
			}
			logger.error("添加渠道费率信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}
	
	/**
	 * 计算费率
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("reckChannelRate")
	public String reckChannelRate(HttpServletRequest request,
			HttpServletResponse response, Model model, ChannelReport channelReport) {
		//Map<String, Object> params =this.getParameters(request);
		
		HashMap<String, Object> params = this.getParametersO(request);
		model.addAttribute("params", params);
		String url=null;
		ChannelRate channelRate= new ChannelRate();
		ChannelInfo channelInfo=new ChannelInfo();
		try {
			 if (params.containsKey("id")) {
						// 更新的页面跳转
				 		HashMap<String, Object> queryMap = new HashMap<String, Object>();
				 		HashMap<String, Object> queryMap1 = new HashMap<String, Object>();				 		
				 		
				 		channelReport = channelReportService.getChannelReportById(channelReport.getId());
				 		queryMap1.put("id",channelReport.getChannelid());
				 		channelInfo = channelInfoService.findOneChannelInfo(queryMap1);
				 		
				 		if(channelInfo==null&&channelInfo.getRateId()==null){
				 			SpringUtils.renderDwzResult(response, false,"该渠道没有配置计算公式，请配置", DwzResult.CALLBACK_CLOSECURRENT,params.get("parentId")
									.toString());
				 		}
				 		queryMap.put("id", channelInfo.getRateId());
				 		channelRate = channelInfoService.findOneChannelRateInfo(queryMap);
				 		
				 		
				 		
				 		BigDecimal money = BigDecimal.ZERO;
				 		money=new BigDecimal(channelReport.getRegisterCount()).multiply(channelRate.getChannelRegisterRate())
				 				.add(((channelReport.getNewIntoMoney()).multiply(channelRate.getChannelNewloanRate())).divide(new BigDecimal(100), 0,
				 						BigDecimal.ROUND_HALF_UP));
				 		model.addAttribute("channelInfo",channelInfo);
						model.addAttribute("channelRate", channelRate);
						model.addAttribute("money", money);
						model.addAttribute("channelReport", channelReport);
			}
			url = "channel/finChannelRate";
			 
		} catch (Exception e) {
			logger.error("againReport error", e);
		}
		return url;
	}
	
	
//	@RequestMapping("getChannelReportChar")
//	public String getChannelReportChar(HttpServletRequest request,
//			HttpServletResponse response, Model model) {
//		try {
//			HashMap<String, Object> params = getParametersO(request);
//			HashMap<String, Object> chMap = new HashMap<String, Object>();
//			BackUser backUser = this.loginAdminUser(request);
//			Object channelid = params.get("channelid");
//			Object endTime = params.get("endTime");
//			Object beginTime = params.get("beginTime");
//			List<ChannelReport> channelReportList = new ArrayList<ChannelReport>();
//			if(channelid!=null&&beginTime!=null&&endTime!=null){
//				channelReportList = channelReportService.getAllChannelReports(params);
//			}
//			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
//			
//			ChannelReport channelReport = new ChannelReport();
//			String[] channelReportDates = new String[channelReportList.size()] ;
//			int[] registerCounts = new int[channelReportList.size()] ;
//			StringBuilder sbu=new StringBuilder();
//			String str="";
//			String aaa= "";
//			JSONObject json = new JSONObject();
//			if(channelReportList.size()>0){
//				int j=7;
//				if(channelReportList.size()<7){
//					j=channelReportList.size();
//				}
//				for (int i = 0; i < j; i++) {
//					channelReport = channelReportList.get(i);
//					if(channelReport!=null){
//						channelReportDates[i]= DateUtil.getDateFormat(channelReport.getReportDate(),"yyyy-MM-dd HH:mm:ss");
//						sbu.append(channelReport.getRegisterCount()).append(",");
//						registerCounts[i] = channelReport.getRegisterCount();
//					}
//					
//				}
//				if(sbu!=null&&sbu.length()>0){
//					str=sbu.toString().substring(0, sbu.length()-1);
//				}
//				
//			}
//			
//			HashMap<String, Object>  xxMap = new HashMap<String, Object>();
//			xxMap.put("name", "注册人数");
//			xxMap.put("data", registerCounts);
//			HashMap<String,Object> map = new HashMap<String, Object>();
//			map.put("series", xxMap);
//			model.addAttribute("series",FastJsonUtils.toJson(xxMap));
//			model.addAttribute("aaa",FastJsonUtils.toJson(aaa));
//			model.addAttribute("channelReportDates", channelReportDates);
//			model.addAttribute("registerCounts",str);
//			//model.addAttribute("registerCounts", FastJsonUtils.toJson(registerCounts));
//			model.addAttribute("channelList", channelList);
//			model.addAttribute("channelReportList", channelReportList);
//			model.addAttribute("params", params);// 用于搜索框保留值
//
//		} catch (Exception e) {
//			logger.error("getChannelReportPage error", e);
//		}
//		return "channel/channelReportChar";
//	}
	
	/**
	 * 根据type跳转到对应的视图
	 */
	@RequestMapping("getChannelReportChar")
	public String getChannelReportChar(HttpServletResponse response,
			HttpServletRequest request, Model model, String type)
			throws Exception {
		Map<String, Object> requests = this.getParametersO(request);
		Map<String, String> params = new HashMap<String, String>();
		try {
			List<ChannelInfo> channelList = channelInfoService.findAll(requests);
		 
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date today = new Date();
			params.put("beginTime", sdf.format(DateUtil.addDay(today, -14)));
			params.put("endTime", sdf.format(today));
			if(channelList!=null&&channelList.size()>0){
				params.put("channelid","0");
			}
			model.addAttribute("channelList", channelList);
			model.addAttribute("params", params);
			 
		} catch (Exception e) {
			logger.error("chartsDispatcher error params:" + requests, e);
		}
		return "channel/channelReportChar";
	}
	
	/**
	 * 查看分析图<br>
	 * @param request
	 * @param response
	 * @param model
	 * @param totalJson
	 */
	@RequestMapping("getChannelChar")
	public void getChannelReportChar(HttpServletRequest request,
			HttpServletResponse response,Model model, TotalJson totalJson) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			HashMap<String, Object> chMap = new HashMap<String, Object>();
			BackUser backUser = this.loginAdminUser(request);
			Object channelid = params.get("channelid");
			Object endTime = params.get("endTime");
			Object beginTime = params.get("beginTime");
			List<ChannelReport> channelReportList = new ArrayList<ChannelReport>();
			if(channelid!=null&&beginTime!=null&&endTime!=null){
				channelReportList = channelReportService.getAllChannelReports(params);
			}
			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			
			ChannelReport channelReport = new ChannelReport();
		 
			JSONObject json = new JSONObject();
			List<String> categoriesDate = new ArrayList<String>();
			SeriesObj vipObj = new SeriesObj("注册人数");
			SeriesObj regObj = new SeriesObj("实名人数");
			SeriesObj pcObj = new SeriesObj("借款人数");
			if(channelReportList!=null&&channelReportList.size()>0){
				List<Integer> countVip = new ArrayList<Integer>();
				List<Integer> countReg = new ArrayList<Integer>();
				List<Integer> countPcReg = new ArrayList<Integer>();
				int j=14;
				if(channelReportList.size()<14){
					j=channelReportList.size();
				}
				for (int i = 0; i < j; i++) {
					channelReport = channelReportList.get(i);
					if(channelReport!=null){
						countVip.add(channelReport.getRegisterCount());
						countReg.add(channelReport.getAlipayCount());
						countPcReg.add(channelReport.getBorrowApplyCount());
//						channelReportDates[i]= DateUtil.getDateFormat(channelReport.getReportDate(),"yyyy-MM-dd HH:mm:ss");
						categoriesDate.add(DateUtil.getDateFormat(channelReport.getReportDate(),"yy-MM-dd"));
					}
				}
				vipObj.setData(countVip);
				regObj.setData(countReg);
				pcObj.setData(countPcReg);
			}
			totalJson.setCategories(categoriesDate);
			totalJson.setSeriesObj(Arrays.asList(regObj, pcObj,vipObj));
			 
		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		model.addAttribute("params", params);
		SpringUtils.renderJson(response, totalJson);
	}

	/**
	 *  New查看推广员
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("ChannelUserInfoPage")
	public String ChannelUserInfoPage(HttpServletRequest request,
									  HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = getParametersO(request);
			BackUser backUser = this.loginAdminUser(request);
			if (backUser != null
					&& !StringUtils.isBlank(backUser.getUserAddress())) {
				HashMap<String, Object> pm = new HashMap<String, Object>();

				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo = channelInfoService
						.findOneChannelInfo(pm);
				if (channelInfo != null) {
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelInfo> pageConfig = channelInfoService.findUserAllPage(params);

			List<ChannelInfo> channelList = channelInfoService.findAllUserList(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			String bpath = request.getContextPath();
			model.addAttribute("bpath", bpath);

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelListInfoPage";
	}
}
